Page({
  data: {
    order: {
      carId: null,
      carName: '',
      carDesc: '',
      price: 0,
      image: '',
      pickupTime: '',
      returnTime: '',
      days: 0,
      baseFee: 0,
      deposit: 0,
      totalFee: 0,
      rentalTypeId: null,
      orderStatus: 0
    },
    user: {
      name: '',
      phone: '',
      idCard: ''
    },
    btnLoading: false
  },
  onLoad(options) {
    if (options.order) {
      try {
        const order = JSON.parse(decodeURIComponent(options.order));
        this.setData({
          order: order
        });
        console.log(order);
      } catch (error) {
        console.error('解析订单数据出错:', error);
      }
    } else {
      console.log('未接收到订单数据');
    }
    
    // 获取用户信息
    this.loadUserInfo();
  },
  
  // 加载用户信息
  loadUserInfo() {
    // 从本地存储获取用户信息
    const userInfo = wx.getStorageSync('userId');
    if (userInfo) {
      this.setData({
        user: {
          name: userInfo.name || '未知',
          phone: userInfo.phone || '未知',
          idCard: userInfo.idCard || '未知'
        }
      });
    } else {
      console.log('未找到用户信息，使用默认值');
    }
  },
  
  // 提交订单
  submitOrder() {
    console.log('提交订单');
    console.log(this.data.order);
    console.log(this.data.user);
    if (this.data.btnLoading) return;
    
    this.setData({ btnLoading: true });
    
    wx.showLoading({
      title: '提交中...'
    });
    
    const app = getApp();
    const token = wx.getStorageSync('token');
    
    if (!token) {
      wx.hideLoading();
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      
      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/login/login'
        });
      }, 1500);
      return;
    }

    const userId = wx.getStorageSync('userId');
    if (!userId) {
      wx.hideLoading();
      wx.showToast({
        title: '用户信息获取失败，请重新登录',
        icon: 'none'
      });
      
      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/login/login'
        });
      }, 1500);
      return;
    }
    // 转换日期时间格式
    const formatDateTime = (dateTime) => {
      if (!dateTime) return '';
      const date = new Date(dateTime);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    };

    // 准备订单数据，确保日期格式正确
    const orderData = {
      autoId: parseInt(this.data.order.autoId),
      customerId: wx.getStorageSync('userId'), // 假设有用户ID存储
      //customerId: parseInt(this.data.order.customerId),
      // 使用yyyy-MM-dd HH:mm:ss格式的日期时间
      rentalTime: formatDateTime(this.data.order.rentalTime),
      returnTime: formatDateTime(this.data.order.returnTime),
      typeId: parseInt(this.data.order.typeId),
      rent: parseInt(this.data.order.price),
      deposit: parseInt(this.data.order.deposit),
      rentPayable: parseInt(this.data.order.totalFee),
      orderStatus: this.data.order.orderStatus = 0,
      mileage: 0 
    };
  
    // 数据校验
    if (!orderData.autoId || !orderData.rentalTime || !orderData.typeId) {
      console.log('订单数据不完整:', orderData);
      wx.hideLoading();
      this.setData({ btnLoading: false });
      wx.showToast({
        title: '订单信息不完整，请检查',
        icon: 'none'
      });
      return;
    }
    
    console.log('提交订单数据:', orderData);
    
    // 调用订单创建API
    wx.request({
      url: `${app.globalData.baseUrl}/rental/order`,
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'token': token
      },
      data: orderData,
      success: (res) => {
        wx.hideLoading();
        this.setData({ btnLoading: false });
        
        console.log('创建订单响应:', res.data);
        
        if (res.statusCode === 200 && res.data && res.data.success) {
          const orderId = res.data.data; // 假设返回的是订单ID
          
          wx.showToast({
            title: '订单创建成功',
            icon: 'success',
            duration: 2000,
            success: () => {
              // 跳转到支付页面或订单列表
              setTimeout(() => {
                wx.redirectTo({
                  url: `/pages/my-orders/my-orders?refresh=true`
                });
              }, 1500);
            }
          });
        } else {
          wx.showToast({
            title: res.data.message || '创建订单失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
        wx.hideLoading();
        this.setData({ btnLoading: false });
        
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      }
    });
  }
});